import camelcaseKeys = require("camelcase-keys");
import { IAppOption } from "./appoption";
import { auth } from "./service/proto_gen/auth_pb";
import { getSetting, getUserInfo } from "./utils/wxapi";

let resolveUserInfo: (value: WechatMiniprogram.UserInfo | PromiseLike<WechatMiniprogram.UserInfo>) => void
let rejectUserInfo: (reason?: any) => void

App<IAppOption>({
  globalData: {
    userInfo: new Promise( (resolve, reject) => {
      resolveUserInfo = resolve;
      rejectUserInfo = reject
    }),
  },
  async onLaunch(){
    wx.login({
      success: res => {
        wx.request({
          url: 'http://localhost:8080/v1/auth/login',
          method: 'POST',
          data: {
            code: res.code,
          } as auth.v1.ILoginRequest,
          success: res => {
            const loginResp: auth.v1.ILoginResponse = auth.v1.LoginResponse.fromObject(
              camelcaseKeys( res.data as object),
            )
            console.log(loginResp)
          },
          fail: console.error,
        })
      }
    })
    
    getSetting().then( res => {
      if( res.authSetting['scope.userInfo']) {
        return getUserInfo()
      }
      
      return undefined
    }).then( res => {
      if( !res){
        return 
      }
      resolveUserInfo(res.userInfo)
    }).catch( err => {
      rejectUserInfo(err)
    })
    
  },
  resolveUserInfo(userInfo:WechatMiniprogram.UserInfo){
    resolveUserInfo(userInfo)
  }
})